﻿//
// Created by Administrator on 2022/1/17.
//

#include "MyApp.h"

#include "MyApp.h"
#include <iostream>
#include <thread>
#include <wx/txtstrm.h>

wxDEFINE_EVENT(wxMY_EVT_1, wxThreadEvent);

wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit()
{
    // 单一进程实例的实现，必须在堆上新建checker，保持活性才会让另一个进程检测到
    m_checker = new wxSingleInstanceChecker();
    if (m_checker->IsAnotherRunning()) {
        delete m_checker;
        m_checker = nullptr;
        return false;
    }
    // 获取User32.dll的MessageBox方法
    if (m_dynlib.Load(wxT("User32.dll"))) {
        if (m_dynlib.HasSymbol(wxT("MessageBoxA"))) {
            using msgBoxType = int __stdcall(int, const wchar_t*, const wchar_t*, int);
            msgBoxType* msgBox = (msgBoxType*)m_dynlib.GetSymbolAorW(wxT("MessageBox"));
            msgBox(NULL, wxT("消息内容"), wxT("消息标题"), 0);
        }
    }
    // wxProcess使用，异步读取另一个程序的标准输出
    m_process = new wxProcess(this);
    m_process->Redirect();
    wxExecute(wxT("cmd /k \"D:\\cpp\\pro\\win32demo1\\Debug\\win32demo1.exe\""),wxEXEC_ASYNC, m_process);
    wxInputStream *inputStream = (m_process->GetInputStream());
    wxTextInputStream tis( *inputStream );
    wxString buf = tis.ReadLine();
    // 临时开启一个detach线程，来模拟发送线程事件
    std::thread t([this]() {
        wxThreadEvent evt(wxMY_EVT_1);
        evt.SetString(wxT("I am a thread."));
        this->QueueEvent(evt.Clone());
    });
    t.detach();
    // 调用父类默认的初始化函数，初始化一些命令行参数注入等
    return __super::OnInit();
}

int MyApp::OnExit()
{
    delete m_checker;
    return 0;
}

int MyApp::FilterEvent(wxEvent& event)
{
    if (event.GetEventType() == wxMY_EVT_1) {
        wxThreadEvent * evt = (wxThreadEvent *)&event;
        wxLogDebug(wxT("Receive a thread event string: %s"), evt->GetString());
    }
    return __super::FilterEvent(event);
}

void MyApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    parser.AddOption(wxT("m"), wxT("name"), wxT("your real name"), wxCMD_LINE_VAL_STRING);
    parser.AddOption(wxT("n"), wxT("age"), wxT("your real age"), wxCMD_LINE_VAL_NUMBER);
    // 默认为/作为选项的前缀的，可以修改为-为前缀
    parser.SetSwitchChars(wxT("-"));
    // 调用基类，提供了一些标准的选项或参数，诸如--help等等
    __super::OnInitCmdLine(parser);
}

bool MyApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
    //获取m参数
    wxString param_m;
    if (parser.Found(wxT("m"))) {
        wxLogDebug(param_m);
    }
    //获取f参数
    long param_f;
    if (parser.Found(wxT("n"))) {
        wxLogDebug(wxT("%d"), param_f);
    }
    // 返回false，这会让OnInit返回false来结束程序
    // 返回true，继续执行程序
    return true;
}

bool MyApp::OnCmdLineHelp(wxCmdLineParser& parser)
{
    std::cout << parser.GetUsageString() << std::endl;
    // 返回false，这会让OnInit返回false来结束程序
    // 返回true，继续执行程序
    return true;
}

bool MyApp::OnCmdLineError(wxCmdLineParser& parser)
{
    // 返回false，这会让OnInit返回false来结束程序
    // 返回true，继续执行程序
    return true;
}

